package com.xoa.service.attend;

import com.alibaba.fastjson.JSONArray;
import com.xoa.dao.attend.AttendLeaveMapper;
import com.xoa.dao.attend.AttendanceOvertimeMapper;
import com.xoa.dao.attendance.AttendRuleMapper;
import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.flowhook.FlowHookMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dao.workflow.FlowRunMapper;
import com.xoa.dao.workflow.FlowRunPrcsMapper;
import com.xoa.model.attend.AttendFlowRunPrcs;
import com.xoa.model.attend.AttendLeave;
import com.xoa.model.attend.AttendanceOvertime;
import com.xoa.model.attendance.AttendRule;
import com.xoa.model.common.SysCode;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.FlowFast;
import com.xoa.model.workflow.FlowHook;
import com.xoa.model.workflow.FlowRun;
import com.xoa.model.workflow.FlowRunPrcs;
import com.xoa.service.WFE.WFERunner.WFEFlowRunInfo;
import com.xoa.service.attend.wrapper.AttendSetWrappers;
import com.xoa.service.work.WorkService;
import com.xoa.util.*;
import com.xoa.util.common.L;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.common.wrapper.BaseWrappers;
import com.xoa.util.dataSource.ContextHolder;
import com.xoa.util.ipUtil.IpAddr;
import com.xoa.util.page.PageParams;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.http.HttpResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.xmlbeans.impl.xb.xsdschema.All;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by gsb on 2017/7/17.
 */
@Service
public class AttendLeaveService {
    @Autowired
    private AttendLeaveMapper attendLeaveMapper;//请假
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private SysCodeMapper sysCodeMapper;
    @Autowired
    private FlowRunPrcsMapper flowRunPrcsMapper;
    @Autowired
    private FlowRunMapper flowRunMapper;
    @Autowired
    private WFEFlowRunInfo wfeFlowRunInfo;

    @Autowired
    private AttendRuleMapper attendRuleMapper;
    @Autowired
    private AttendanceOvertimeMapper attendanceOvertimeMapper;

    public final String dateTime = "0";

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017-7-14 下午14:45:00
     * 方法介绍:   查询请假登记
     */
    public ToJson<AttendFlowRunPrcs> queryAllAttendLeave(Integer page, Integer pageSize,
                                                   Boolean useFlag,HttpServletRequest request,String FlowAllow){
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
        Map<String, Object> objectMap = new HashMap<String, Object>();
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        objectMap.put("page", pageParams);
        objectMap.put("userId", users.getUserId());
        objectMap.put("flowAllow",FlowAllow);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ToJson<AttendFlowRunPrcs> json = new ToJson<AttendFlowRunPrcs>(1, "error");
        try{
            List<AttendFlowRunPrcs> attendLeaveList=attendLeaveMapper.queryAllAttendLeave(objectMap);
            for (AttendLeave attendLeave:attendLeaveList){

                if(!StringUtils.checkNull(attendLeave.getUserId())) {
                    if(usersMapper.findUsersByuserId(attendLeave.getUserId())!=null){
                        attendLeave.setUserName(usersMapper.findUsersByuserId(attendLeave.getUserId()).getUserName());
                    }
                    if(usersMapper.findUsersByuserId(attendLeave.getUserId())!=null){
                        if(departmentMapper.getDeptNameById(usersMapper.findUsersByuserId(attendLeave.getUserId()).getDeptId())!=null){
                            attendLeave.setDeptName(departmentMapper.getDeptNameById(usersMapper.findUsersByuserId(attendLeave.getUserId()).getDeptId()));
                        }
                    }
                }

                if(!StringUtils.checkNull(attendLeave.getAgent())){
                    if(usersMapper.findUsersByuserId(attendLeave.getAgent())!=null){
                        attendLeave.setAgent(usersMapper.findUsersByuserId(attendLeave.getAgent()).getUserName());
                    }
                }
               if(!StringUtils.checkNull(attendLeave.getStatus())){
                   int status=Integer.valueOf(attendLeave.getStatus());
                   switch (status){
                       case 1:
                           attendLeave.setStatus("未确认");
                           break;
                       case 2:
                           attendLeave.setStatus("确认销假");
                           break;
                   }
               }
               if(!StringUtils.checkNull(attendLeave.getAllow())){
                   int allow=Integer.valueOf(attendLeave.getAllow());
                   switch (allow){
                       case 0:
                           attendLeave.setAllow("待审批");
                           break;
                       case 1:
                           attendLeave.setAllow("已批准");
                           break;
                       case 2:
                           attendLeave.setAllow("未批准");
                           break;
                       case 3:
                           attendLeave.setAllow("申请销假");
                           break;
                   }
               }
               if(!StringUtils.checkNull(attendLeave.getLeaveType2())){
                   int leaveType2=Integer.valueOf(attendLeave.getLeaveType2());
                   switch (leaveType2){
                       case 1:
                           attendLeave.setLeaveType2("事假");
                           break;
                       case 2:
                           attendLeave.setLeaveType2("病假");
                           break;
                       case 3:
                           attendLeave.setLeaveType2("年假");
                           break;
                   }
               }
               if(attendLeave.getLeaveDate1()!=null&&attendLeave.getLeaveDate1()!=null){
                   attendLeave.setBeginDate(DateFormat.getStrDate(attendLeave.getLeaveDate1()));
                   attendLeave.setEndDate(DateFormat.getStrDate(attendLeave.getLeaveDate2()));
                   long begin= DateFormat.getTime(sdf.format(attendLeave.getLeaveDate1()));
                   long end=DateFormat.getTime(sdf.format(attendLeave.getLeaveDate2()));
                   attendLeave.setLeaveTime(DateFormat.returnTime((int)(end-begin)));
               }else {
                   attendLeave.setBeginDate("");
                   attendLeave.setEndDate("");
                   attendLeave.setLeaveTime("");
               }
                FlowRunPrcs flowRunPrcs= flowRunPrcsMapper.queryByRunId(attendLeave.getRunId());
                if(flowRunPrcs!=null){
                    attendLeave.setFlowPrcs(flowRunPrcs.getFlowPrcs().toString());
                    attendLeave.setPrcsId(flowRunPrcs.getPrcsId().toString());
                }else {
                    attendLeave.setFlowPrcs("");
                    attendLeave.setPrcsId("");
                }
                FlowRun flowRun=flowRunMapper.find(attendLeave.getRunId());
                if(flowRun!=null){
                    attendLeave.setRunId(flowRun.getRunId());
                }
            }

            json.setObj(attendLeaveList);
            json.setMsg("ok");
            json.setFlag(0);
            json.setTotleNum(pageParams.getTotal());
        }catch(Exception e){
            json.setMsg(e.getMessage());
            L.e("AttendService queryAllAttendLeave:"+e);
        }
        return  json;
    }

    public ToJson<AttendLeave> queryAllAttendLeaveFields(String tableName,HttpServletRequest req){
        Cookie redisSessionId = CookiesUtil.getCookieByName(req, "redisSessionId");
        String sqlType = "xoa" +SessionUtils.getSessionInfo(req.getSession(), "loginDateSouse", String.class, redisSessionId);

        ToJson<AttendLeave> json = new ToJson<AttendLeave>(1, "error");
        Map<String,Object>  map=new HashMap<String,Object>();
        map.put("tableName",tableName);
        map.put("sqlType",sqlType);
        List<AttendLeave> attendLeaveList=attendLeaveMapper.queryAllAttendLeaveFields(map);
        if (attendLeaveList!=null&&attendLeaveList.size()>0){
           /* Iterator<AttendLeave> attendLeaveIterator=attendLeaveList.iterator();
            while (attendLeaveIterator.hasNext()){
                AttendLeave attendLeave=attendLeaveIterator.next();

                if("LEAVE_ID".equals(attendLeave.getColumnName())){
                    attendLeave.setColumnName("leaveId");
                }else if ("USER_ID".equals(attendLeave.getColumnName())){
                    attendLeave.setColumnName("userId");
                }else if ("LEADER_ID".equals(attendLeave.getColumnName())){
                    attendLeave.setColumnName("leaderId");
                }else if ("LEAVE_TYPE".equals(attendLeave.getColumnName())){
                    attendLeave.setColumnName("leaveType");
                }else if ("LEAVE_DATE1".equals(attendLeave.getColumnName())){
                    attendLeave.setColumnName("leaveDate1");
                }else if ("LEAVE_DATE2".equals(attendLeave.getColumnName())){
                    attendLeave.setColumnName("leaveDate2");
                }else if ("ANNUAL_LEAVE".equals(attendLeave.getColumnName())){
                    attendLeave.setColumnName("annualLeave");
                }else if ("STATUS".equals(attendLeave.getColumnName())){
                    attendLeave.setColumnName("status");
                }else if ("ALLOW".equals(attendLeave.getColumnName())){
                    attendLeave.setColumnName("allow");
                }else if ("REASON".equals(attendLeave.getColumnName())){
                    attendLeave.setColumnName("reason");
                }else if ("DESTROY_TIME".equals(attendLeave.getColumnName())){
                    attendLeave.setColumnName("destroyTime");
                }else if ("REGISTER_IP".equals(attendLeave.getColumnName())){
                    attendLeave.setColumnName("registerIp");
                }else if ("RECORD_TIME".equals(attendLeave.getColumnName())){
                    attendLeave.setColumnName("recordTime");
                }else if ("LEAVE_TYPE2".equals(attendLeave.getColumnName())){
                    attendLeave.setColumnName("leaveType2");
                }else if ("HANDLE_TIME".equals(attendLeave.getColumnName())){
                    attendLeave.setColumnName("handleTime");
                }else if ("AGENT".equals(attendLeave.getColumnName())){
                    attendLeave.setColumnName("agent");
                }else if ("ORDER_NO".equals(attendLeave.getColumnName())){
                    attendLeave.setColumnName("orderNo");
                }
            }*/

            json.setObj(attendLeaveList);
            json.setMsg("ok");
            json.setFlag(0);
            return  json;
        }
        return  json;
    }
    public BaseWrapper addAttendLeave(String userId,String recordTime,HttpServletRequest request){
        AttendSetWrappers wrappers = new AttendSetWrappers();
        AttendLeave attendLeave=new AttendLeave();
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user=SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
        String  sqlType = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
     List<SysCode>  sysCodes= sysCodeMapper.getSysCode("KQQJTYPE");
        for(SysCode sysCode:sysCodes){
            if(sysCode.getCodeName().equals("请假申请")){
                ToJson<FlowFast> flowFastToJson=  wfeFlowRunInfo.workFastAdd(user, Integer.parseInt(sysCode.getCodeNo()) ,1,"1","",request,sqlType,"",null);
                 if(flowFastToJson.isFlag()){
                     if(StringUtils.checkNull(userId)){
                         Users users =SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
                         attendLeave.setUserId(users.getUserId());
                     }else {
                         attendLeave.setUserId(userId);
                     }
                     FlowFast flowFast=(FlowFast)flowFastToJson.getObject();
                     attendLeave.setRunId(flowFast.getFlowRun().getRunId());
                     attendLeave.setRecordTime(DateFormat.getDate(recordTime));
                     attendLeave.setRegisterIp(IpAddr.getIpAddress(request));
                     attendLeave.setTableName("attend_leave");
                     attendLeave.setAllow("0");
                     attendLeave.setStatus("1");
                     // attendLeave.setFolwId(flowHook.getFlowId().toString());
                     AttendLeave attendLeave1 =  attendLeaveMapper.selectAttendByRunId(flowFast.getFlowRun().getRunId());
                     if(attendLeave1 !=null ){
                         attendLeaveMapper.deleteAttendKey(attendLeave1.getLeaveId());
                     }
                     int amount=attendLeaveMapper.addAttendLeave(attendLeave);
                     if(amount>0){
                         attendLeave.setFlowId(flowFast.getFlowTypeModel().getFlowId().toString());
                         attendLeave.setFlowName(flowFast.getFlowTypeModel().getFlowName());
                         wrappers.setFlag(true);
                         wrappers.setStatus(true);
                         wrappers.setData(attendLeave);
                         wrappers.setMsg("更新成功");
                     }
                 }
            }

        }




     //   Users user=SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
       /* String  sqlType = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");*/
         // FlowHook flowHook= flowHookMapper.queryByHmodule("attend_leave");
     //   ToJson<FlowFast> tj=workService.workFastAdd(user,flowHook.getFlowId(),1,"",request,sqlType);
    /*    FlowFast f = (FlowFast) tj.getObject();
        if(f!=null){*/


      /*  }*/
        return  wrappers;
    }

    public BaseWrappers backlogAttendList(HttpServletRequest request, String num, Integer page, Integer pageSize,
                                          Boolean useFlag){
        BaseWrappers wrappers =new BaseWrappers();
        wrappers.setStatus(true);
        wrappers.setFlag(false);
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users =SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
        if(StringUtils.checkNull(users.getUserId())){
            wrappers.setMsg("用户信息过期");
            return wrappers;
        }
        Map<String,Object> map=new HashMap<String,Object>();
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        map.put("page", pageParams);
        map.put("userId", users.getUserId());
        wrappers.setTotal(pageParams.getTotal());
        if("1".equals(num)){
            List<AttendFlowRunPrcs> attendFlowRunPrcs=attendLeaveMapper.backlogAttendList(map);

            for(AttendFlowRunPrcs attendFlowRunPrcs1:attendFlowRunPrcs){

                if(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId())!=null){
                    if(departmentMapper.getDeptNameById(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId()).getDeptId())!=null){
                        attendFlowRunPrcs1.setDeptName(departmentMapper.getDeptNameById(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId()).getDeptId()));
                    }
                }
                if(attendFlowRunPrcs1.getLeaveDate1()!=null&&attendFlowRunPrcs1.getLeaveDate1()!=null){
                    attendFlowRunPrcs1.setBeginDate(DateFormat.getStrDate(attendFlowRunPrcs1.getLeaveDate1()));
                    attendFlowRunPrcs1.setEndDate(DateFormat.getStrDate(attendFlowRunPrcs1.getLeaveDate2()));

                }else {
                    attendFlowRunPrcs1.setBeginDate("");
                    attendFlowRunPrcs1.setEndDate("");

                }
                attendFlowRunPrcs1.setTableName("attend_leave");
            }
            wrappers.setFlag(true);
            wrappers.setDatas(attendFlowRunPrcs);
            wrappers.setTotal(pageParams.getTotal());
        }else if("2".equals(num)) {
            List<AttendFlowRunPrcs> attendFlowRunPrcs=attendLeaveMapper.haveDoneAttendList(map);
            for(AttendFlowRunPrcs attendFlowRunPrcs1:attendFlowRunPrcs){

                if(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId())!=null){
                    if(departmentMapper.getDeptNameById(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId()).getDeptId())!=null){
                        attendFlowRunPrcs1.setDeptName(departmentMapper.getDeptNameById(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId()).getDeptId()));
                    }
                }
                if(attendFlowRunPrcs1.getLeaveDate1()!=null&&attendFlowRunPrcs1.getLeaveDate1()!=null){
                    attendFlowRunPrcs1.setBeginDate(DateFormat.getStrDate(attendFlowRunPrcs1.getLeaveDate1()));
                    attendFlowRunPrcs1.setEndDate(DateFormat.getStrDate(attendFlowRunPrcs1.getLeaveDate2()));

                }else {
                    attendFlowRunPrcs1.setBeginDate("");
                    attendFlowRunPrcs1.setEndDate("");

                }
                attendFlowRunPrcs1.setTableName("attend_leave");
            }
            wrappers.setFlag(true);
            wrappers.setDatas(attendFlowRunPrcs);
            wrappers.setTotal(pageParams.getTotal());
        }

      return  wrappers;
    }


    public BaseWrapper getAllByDate(String startDate,String endDate,Integer length,String userId){
        BaseWrapper baseWrapper = new BaseWrapper();
        GregorianCalendar calendar=new GregorianCalendar();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        if(length!=null && length>0){
            calendar.setTime(new Date());
            endDate=sdf.format(calendar.getTime());
            calendar.add(2,-length);
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            startDate=sdf.format(calendar.getTime());
        }

        HashMap<String,Object> param = new HashMap<>();
        param.put("startDate",startDate);
        param.put("endDate",endDate);
        param.put("userId",userId);
        List<AttendLeave> attendLeaves = attendLeaveMapper.getAllByDate(param);

        sdf = new SimpleDateFormat("yyyy-MM");
        Map<String,Integer> temp=new HashMap<>();
        for(AttendLeave a:attendLeaves){
            Date date = a.getLeaveDate1();
            String key = "unKnown";
            if(date!=null){
                key = sdf.format(date);
            }
            if(temp.containsKey(key)){
                temp.put(key,temp.get(key)+1);
            }else{
                temp.put(key,1);
            }
        }
//        List<Map<String,Object>> data = new ArrayList<Map<String, Object>>();
//        for( String key: temp.keySet()){
//            Map<String,Object> item =new HashedMap();
//            if("unKnown".equals(key)){
//                String[] keys = key.split("-");
//                item.put("years",keys[0]);
//                item.put("month",keys[1]);
//                item.put("key",key);
//                item.put("count",temp.get(key));
//            }else{
//                item.put(key,temp.get(key));
//            }
//            data.add(item);
//        }
        baseWrapper.setData(temp);
        return baseWrapper;
    }
    /**
     * 创建人：季佳伟
     * 创建时间：2017-11-21  下午5:40:17
     * 方法介绍：查询登录人一段时间内的请假状况
     * 参数说明：
     */
    public ToJson<AttendLeave> selectAttendLeaveByUserId(String beginDate, String endDate,HttpServletRequest req){
        ToJson<AttendLeave> json = new ToJson<AttendLeave>();
        try {
            Cookie redisSessionId = CookiesUtil.getCookieByName(req, "redisSessionId");
            String userId = SessionUtils.getSessionInfo(req.getSession(), Users.class, new Users(),redisSessionId).getUserId();
            List<Date> dates = DateCompute.getBetweenDates(DateFormat.DateToStr(beginDate), DateFormat.DateToStr(endDate));
            List<AttendLeave> attendLeaveList = attendLeaveMapper.selectAttendLeaveByUserId(userId);
            List<AttendLeave> newAttendLeaveList = new ArrayList<AttendLeave>();
            if(attendLeaveList.size() > 0){
                for(AttendLeave attendLeave : attendLeaveList){
                    for (Date nowDate : dates){
                        String aTime = DateFormat.getDatestr(attendLeave.getRecordTime()).substring(0,10);
                        String nTime = DateFormat.getDatestr(nowDate);
                        if(aTime.equals(nTime)){
                            newAttendLeaveList.add(attendLeave);

                        }
                    }
                }
                json.setObj(newAttendLeaveList);
                json.setFlag(0);
                json.setMsg("ok");
            }else {
                json.setFlag(1);
                json.setMsg("err");

            }


        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg("err");
        }
        return json;
    }
    public BaseWrapper getAttendLeaveCount(){
        AttendSetWrappers wrappers = new AttendSetWrappers();
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        List<AttendLeave> attendLeaves=attendLeaveMapper.getAttendLeaveCount(String.valueOf(year));
        wrappers.setData(attendLeaves);
        wrappers.setFlag(true);
        wrappers.setStatus(true);
        wrappers.setMsg("更新成功");
        return  wrappers;
    }

    /**
     * 左春晖
     * 导出请假记录
     */

@SuppressWarnings("all")
    public ToJson<AttendLeave> queryExportAttend(HttpServletRequest request, HttpServletResponse response, AttendLeave attendLeave,String beginDate, String isExport,Integer page, Integer pageSize, Boolean useFlag) {
        ToJson<AttendLeave> json = new ToJson<AttendLeave>();

        try {
            Map<String,Object> map = new HashMap<String,Object>();
            PageParams pageParams = new PageParams();
            pageParams.setUseFlag(useFlag);//是否分页
            pageParams.setPage(page);//当前页
            pageParams.setPageSize(pageSize);//每页条数
            if ("yes".equals(isExport)){
                map.put("beginDate",beginDate);
            }else{
                map.put("page",pageParams);
                map.put("beginDate",beginDate);
            }
            List<AttendLeave> attendLeaveList=attendLeaveMapper.queryAttendLeaves(map);
            for (int i =0; i<attendLeaveList.size();i++){
                AttendLeave attendLeave1 = attendLeaveList.get(i);
                int  number = DateFormat.getTime(DateFormat.getStrDate(attendLeave1.getLeaveDate2()))-DateFormat.getTime(DateFormat.getStrDate(attendLeave1.getLeaveDate1()));
               attendLeave1.setNumber(DateFormat.returnTime(number));
               String type1 = attendLeave1.getLeaveType2();
               switch (type1){
                   case "1":
                       attendLeave1.setLeaveType2("事假");
                       break;
                   case "2":
                       attendLeave1.setLeaveType2("病假");
                       break;
                   case "3":
                       attendLeave1.setLeaveType2("年假");
                       break;
                   case "9":
                       attendLeave1.setLeaveType2("其他");
                       break;
                   default:
                       attendLeave1.setLeaveType2(type1);
                       break;
               }
            }
            if (attendLeaveList != null) {
                json.setTotleNum(pageParams.getTotal());//总条数
                json.setObj(attendLeaveList);
                json.setFlag(0);
                json.setTurn(true);
                json.setMsg("ok");
            } else {
                json.setFlag(1);
                json.setMsg("err");
            }
            if ("yes".equals(isExport)){
            HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("请假信息", 6);
            String[] secondTitles = {"姓名", "年级",  "请假类型", "请假时间","请假天数","备注"};
            HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
            String[] beanProperty = {"userName", "deptName","leaveType2", "leavesDate1", "number"};

            HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, attendLeaveList, beanProperty);
            ServletOutputStream out = response.getOutputStream();

            String filename = "请假信息表.xls";
            filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-disposition", "attachment;filename=" + filename);
            workbook.write(out);
            out.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }

    /**
     * 判断是否可以调休
     * @param userId
     * @return
     */
    public ToJson queryPaidLeave(String userId) {
        ToJson toJson = new ToJson();
        try {
            //通过用户id获取一月加班登记集合
            List<AttendanceOvertime> attendanceOvertimeList = attendanceOvertimeMapper.selAttendanceOvertimeByUserId(userId);
            double overTimes = 0.0;//总价加班时长
            for (int i = 0; i < attendanceOvertimeList.size(); i++) {
                AttendanceOvertime attendanceOvertime = attendanceOvertimeList.get(i);
                String hours = attendanceOvertime.getOvertimeHours();
                if (attendanceOvertime.getOvertimeHours() != null && !"".equals(attendanceOvertime.getOvertimeHours())) {
                    double overTime = Double.parseDouble(hours);
                    overTimes = overTimes + overTime;
                }
            }
            //通过用户id获取以一月调休天数
            int days = 0;
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            List<AttendLeave> attendLeaveList = attendLeaveMapper.selAttendLeaveByUserId(userId);
            if (attendLeaveList.size() != 0) {
                for (int i = 0; i < attendLeaveList.size(); i++) {
                    Date begin_date = attendLeaveList.get(i).getLeaveDate1();
                    Date end_date = attendLeaveList.get(i).getLeaveDate2();
                    String leaverType2 = attendLeaveList.get(i).getLeaveType2();
                    if (begin_date != null && leaverType2 != null && end_date != null) {
                        String begin = simpleDateFormat.format(begin_date);
                        begin_date = simpleDateFormat.parse(begin);
                        String end = simpleDateFormat.format(end_date);
                        end_date = simpleDateFormat.parse(end);
                        int day = (int) (end_date.getTime() - begin_date.getTime()) / (24 * 60 * 60 * 1000) + 1;
                        if (day > 0 && !"".equals(day)) {
                            days = days + day;
                        }
                    }
                }
            }
            //获取用户的部门id
            Users users = usersMapper.getUsersByuserId(userId);
            Integer deptId = users.getDeptId();
            String dept = deptId.toString();
            //通过部门id查询部门考勤规则
            if (dept != null) {
                List<AttendRule> attendRules = attendRuleMapper.getAttendRuleList();
                if ("ALL_DEPT".equals(attendRules.get(0).getDeptId())) {
                    AttendRule attendRule = attendRules.get(0);
                    //获取时间和兑换天数
                    int hour = attendRule.getOvertimeHour();
                    if (hour > 0) {
                        double paidLeaveDays = (overTimes / hour);//用户所在部门可调休天数
                        int paidLeaveDay = (int) Math.floor(paidLeaveDays);
                        if (paidLeaveDay >= days) {
                            //剩余调休天数
                            int remainingDay = paidLeaveDay - days;
                            //判断是否可调休
                            if (remainingDay == 0) {
                                remainingDay = 1;
                            }
                            if (remainingDay >= 0) {
                                toJson.setFlag(0);
                                toJson.setObject(remainingDay);
                            }
                        }else {
                            toJson.setFlag(0);
                            toJson.setMsg("不能调休");
                            toJson.setObject(0);
                        }
                    } else {
                        toJson.setFlag(0);
                        toJson.setMsg("不能调休");
                        toJson.setObject(0);
                    }
                }
                if (!"ALL_DEPT".equals(attendRules.get(0).getDeptId())) {
                    int aid = 0;
                    List<AttendRule> attendRulesa = attendRuleMapper.getAttendRuleList();
                    for (AttendRule f : attendRulesa) {
                        String id = f.getDeptId();
                        String[] depts = id.split(",");
                        for (String s : depts) {
                            if (dept.equals(s)) {
                                aid = f.getArid();
                            }
                        }
                    }
                    AttendRule attendRule = attendRuleMapper.selectByPrimaryKey(aid);
                    if (attendRule != null) {
                        //获取时间和兑换天数
                        int hour = attendRule.getOvertimeHour();
                        if (hour > 0) {
                            double paidLeaveDays = (overTimes / hour);//用户所在部门可调休天数
                            int paidLeaveDay = (int) Math.floor(paidLeaveDays);
                            if (paidLeaveDay >= days) {
                                //剩余调休天数
                                int remainingDay = paidLeaveDay - days;
                                //判断是否可调休
                                if (remainingDay == 0) {
                                    remainingDay = 1;
                                }
                                if (remainingDay >= 0) {
                                    toJson.setFlag(0);
                                    toJson.setObject(remainingDay);
                                }
                            } else {
                                toJson.setFlag(0);
                                toJson.setMsg("不能调休");
                                toJson.setObject(0);
                            }
                        } else {
                            toJson.setFlag(0);
                            toJson.setMsg("不能调休");
                            toJson.setObject(0);
                        }
                    }else {
                        toJson.setFlag(0);
                        toJson.setMsg("不能调休");
                        toJson.setObject(0);
                    }
                }
            }
        } catch (Exception e) {
            toJson.setFlag(1);
            toJson.setMsg("no");
        }
        return toJson;
    }

    /**
     * 最近3个月调休总天数
     * @param userId
     * @return           ok
     */
    public ToJson allPaidLeave(String userId){
        ToJson toJson = new ToJson();
        try{
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar calendar = Calendar.getInstance();
            Date now = new Date();//当前时间
            List<AttendLeave> attendLeaveList = attendLeaveMapper.selectAttendLeaveByUserId(userId);
            int days = 0;
            if(attendLeaveList.size() != 0){
                for (int i =0; i < attendLeaveList.size(); i++){
                    Date begin_date = attendLeaveList.get(i).getLeaveDate1();//请假开始时间
                    Date end_date = attendLeaveList.get(i).getLeaveDate2();//请假结束时间
                    String leaveType2 = attendLeaveList.get(i).getLeaveType2();//请假类型
                    if (leaveType2 != null && begin_date != null  ){
                        calendar.setTime(now);
                        calendar.add(Calendar.MONTH,-3);//获取3个月前的时间
                        long time = calendar.getTime().getTime();
                        Long beginTime = begin_date.getTime();
                        if (beginTime > time){
                            end_date = simpleDateFormat.parse(simpleDateFormat.format(end_date));
                            begin_date = simpleDateFormat.parse(simpleDateFormat.format(begin_date));
                            end_date.getTime();
                            begin_date.getTime();
                            int day = (int) (end_date.getTime()-begin_date.getTime())/(1000 * 60 * 60 * 24)+1;
                            days = days + day;
                        }
                    }
                }
            }
            toJson.setObject(days);
            toJson.setFlag(0);
        }catch(Exception e){
            toJson.setFlag(1);
            toJson.setMsg("no");
        }
        return toJson;
    }

}
